package com.childenglish.utils;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

    /**
     * 计算字符串的MD5值
     */
    public static String calculateMD5(String input) {
        if (input == null || input.isEmpty()) {
            return null;
        }

        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hash = digest.digest(input.getBytes());
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不支持", e);
        }
    }

    /**
     * 计算文件的MD5值
     */
    public static String calculateFileMD5(File file) {
        if (file == null || !file.exists() || !file.isFile()) {
            return null;
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            return calculateStreamMD5(fis);
        } catch (IOException e) {
            throw new RuntimeException("计算文件MD5失败", e);
        }
    }

    /**
     * 计算输入流的MD5值
     */
    public static String calculateStreamMD5(InputStream inputStream) throws IOException {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }

            byte[] hash = digest.digest();
            return bytesToHex(hash);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不支持", e);
        }
    }

    /**
     * 计算字节数组的MD5值
     */
    public static String calculateBytesMD5(byte[] data) {
        if (data == null || data.length == 0) {
            return null;
        }

        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hash = digest.digest(data);
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不支持", e);
        }
    }

    /**
     * 验证MD5值是否匹配
     */
    public static boolean verifyMD5(File file, String expectedMD5) {
        if (file == null || expectedMD5 == null) {
            return false;
        }

        String actualMD5 = calculateFileMD5(file);
        return expectedMD5.equalsIgnoreCase(actualMD5);
    }

    /**
     * 验证字符串MD5是否匹配
     */
    public static boolean verifyStringMD5(String input, String expectedMD5) {
        if (input == null || expectedMD5 == null) {
            return false;
        }

        String actualMD5 = calculateMD5(input);
        return expectedMD5.equalsIgnoreCase(actualMD5);
    }

    /**
     * 字节数组转十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 生成随机MD5（用于测试）
     */
    public static String generateRandomMD5() {
        return calculateMD5(String.valueOf(System.currentTimeMillis() + Math.random()));
    }

    /**
     * 获取MD5的前8位（短MD5）
     */
    public static String getShortMD5(String md5) {
        if (md5 == null || md5.length() < 8) {
            return md5;
        }
        return md5.substring(0, 8);
    }
}